from django.shortcuts import render
from django_filters import NumberFilter, ChoiceFilter

from django_filters.rest_framework import DjangoFilterBackend, FilterSet
from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.pagination import PageNumberPagination

from .models import ProvinceModel, CityModel, DepartmentModel, DepartmentCategoryModel, DoctorModel, \
    DoctorEvaluationModel, OperationCategoryModel, OperationModel, TreatmentModel, HospitalModel, QuestionModel, \
    AnswerModel
from .serial import ProvinceSerializer, CitySerializer, DepartmentCategorySerializer, DepartmentSerializer, \
    DoctorSerializer, HospitalSerializer, TreatmentSerializer, OperationCategorySerializer, OperationSerializer, \
    DoctorDetailSerializer, HospitalDetailSerializer, TreatmentDetailSerializer, OperationDetailSerializer, \
    QuestionSerializer, QuestionDetailSerializer, AnswerSerializer

from drf_haystack.viewsets import HaystackViewSet
from drf_haystack.filters import HaystackFilter
from doctors.serial import DoctorIndexHaystackSerializer

# Create your views here.


# class ProvinceView(ListAPIView):
#     queryset = ProvinceModel.objects.filter(is_deleted=False,is_show=True).order_by('id')
#     # queryset = ProvinceModel.objects.all()
#     serializer_class = ProvinceSerializer
#
#
#
# class CityView(ListAPIView):
#     queryset = CityModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
#     serializer_class = CitySerializer
#
# # 科室
# class DepartmentView(ListAPIView):
#     queryset = DepartmentModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
#     serializer_class = DepartmentSerializer
# class DepartmentDetailView(RetrieveAPIView):
#     queryset = DepartmentModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
#     serializer_class = DepartmentSerializer
#
#
# # 科室分类
# class DepartmentCategoryView(ListAPIView):
#     queryset = DepartmentCategoryModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
#     serializer_class = DepartmentCategorySerializer
# class DepartmentCategoryDetailView(RetrieveAPIView):
#     queryset = DepartmentCategoryModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
#     serializer_class = DepartmentCategorySerializer
#
# class DoctorView(ListAPIView):
#     queryset = DoctorModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
#     serializer_class = DoctorSerializer

# 实现了地域查询的接口
class ProvinceView(ListAPIView):
    queryset = ProvinceModel.objects.filter(is_deleted=False,is_show=True).order_by('id')
    serializer_class = ProvinceSerializer


class CityView(ListAPIView):
    serializer_class = CitySerializer
    def get_queryset(self):
        provinceID = int(self.kwargs.get('provinceID',0))
        query_set = CityModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
        if provinceID>0:
            query_set = query_set.filter(province=provinceID)
        elif provinceID==0:
            query_set = query_set.filter(is_hot=True)

        return query_set

class CityDocView(ListAPIView):
    serializer_class = DoctorSerializer
    def get_queryset(self):
        cityID = int(self.kwargs.get('cityID',0))
        query_set = DoctorModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
        if cityID>0:
            query_set = query_set.filter(city=cityID).order_by('-rating')
        # elif cityID==0:
        #     query_set = query_set.filter(city__is_hot=True)
        return query_set


# 问医生
class DepartmentCategoryView(ListAPIView):
    queryset = DepartmentCategoryModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
    serializer_class = DepartmentCategorySerializer

class DepartmentView(ListAPIView):
    serializer_class = DepartmentSerializer
    def get_queryset(self):
        de_categoryID = int(self.kwargs.get('de_categoryID',0))
        query_set = DepartmentModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
        if de_categoryID>0:
            query_set = query_set.filter(category=de_categoryID)

        return query_set


# 定义自定义的过滤器类
class DoctorFilter(FilterSet):
    # 定义挂号费筛选范围

    consultation_price_min = NumberFilter(field_name="consultation_price", lookup_expr='gte')
    consultation_price_max = NumberFilter(field_name="consultation_price", lookup_expr='lte')

    # 城市筛选
    city = NumberFilter(field_name="city")

    # 定义医生职称筛选
    title = ChoiceFilter(choices=DoctorModel.TITLE_CHOICES)  # 使用模型中的选择

    class Meta:
        model = DoctorModel
        fields = ['consultation_price_min', 'consultation_price_max', 'title','city']


class DoctorView(ListAPIView):
    filter_backends = [OrderingFilter,DjangoFilterBackend]
    ordering_fields = ['consultation_count','avg_response_time','rating','consultation_price']
    serializer_class = DoctorSerializer
    filterset_class = DoctorFilter
    def get_queryset(self):
        departmentID = int(self.kwargs.get('departmentID',0))

        query_set = DoctorModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
        if departmentID>0:
            query_set = query_set.filter(department=departmentID)
        return query_set

# 通过医院找医生
# class DoctorByHospitalView(ListAPIView):
#     serializer_class = DoctorSerializer
#     def get_queryset(self):
#         hospitalID = int(self.kwargs.get('hospitalID',0))
#         query_set = DoctorModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
#         if hospitalID>0:
#             query_set = query_set.filter(hospitals=hospitalID)
#         return query_set



class DoctorDetailView(RetrieveAPIView):
    queryset = DoctorModel.objects.all()
    serializer_class = DoctorDetailSerializer
    lookup_field = 'pk'
    lookup_url_kwarg = 'doctorID'
# 这里使用的是 'doctorID'，表示视图会从 URL 参数中提取一个名为 doctorID 的值，作为 lookup_field（主键 pk）的值。
# 例如，如果 URL 是 /api/doctors/1/，其中 1 会作为 doctorID 的值用于查询。

class HospitalView(ListAPIView):

    serializer_class = HospitalSerializer
    def get_queryset(self):
        demartmentID = int(self.kwargs.get('departmentID',0))
        query_set = HospitalModel.objects.filter(is_deleted=False, is_show=True).order_by('level')
        if demartmentID>0:
            query_set = query_set.filter(departments=demartmentID)
        return query_set

class HospitalDetailView(RetrieveAPIView):
    queryset = HospitalModel.objects.all()
    serializer_class = HospitalDetailSerializer
    lookup_field = 'pk'
    lookup_url_kwarg = 'hospitalID'

class TreatmentView(ListAPIView):
    serializer_class = TreatmentSerializer
    def get_queryset(self):
        departmentID = int(self.kwargs.get('departmentID',0))
        query_set = TreatmentModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
        if departmentID>0:
            query_set = query_set.filter(department=departmentID)
        return query_set

class TreatmentDetailView(RetrieveAPIView):
    queryset = TreatmentModel.objects.all()
    serializer_class = TreatmentDetailSerializer
    lookup_field = 'pk'
    lookup_url_kwarg = 'treatmentID'


# class DoctorAnswersView(ListAPIView):
#     serializer_class = DoctorAnswerSerializer
#     def get_queryset(self):
#         doctorID = int(self.kwargs.get('doctorID',0))
#         query_set = DoctorModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
#         if doctorID>0:
#             query_set = query_set.filter(doctors=doctorID)
#         return query_set





class QuestionView(ListAPIView):
    serializer_class = QuestionSerializer
    def get_queryset(self):
        treatmentID = int(self.kwargs.get('treatmentID',0))
        query_set = QuestionModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
        if treatmentID>0:
            query_set = query_set.filter(treatment=treatmentID)

        return query_set

class AnswerView(ListAPIView):
    serializer_class = AnswerSerializer
    def get_queryset(self):
        questionID = int(self.kwargs.get('questionID',0))
        doctorID = int(self.kwargs.get('doctorID',0))
        query_set = AnswerModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
        if questionID>0:
            query_set = query_set.filter(question=questionID)
        if doctorID>0:
            query_set = query_set.filter(doctor=doctorID)
        return query_set


class OperationCategoryView(ListAPIView):
    queryset = OperationCategoryModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
    serializer_class = OperationCategorySerializer

class OperationView(ListAPIView):
    serializer_class = OperationSerializer
    def get_queryset(self):
        opcategoryID = int(self.kwargs.get('opcategoryID',0))
        query_set = OperationModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
        if opcategoryID>0:
            query_set = query_set.filter(category=opcategoryID)
        return query_set

class OperationDetailView(RetrieveAPIView):
    queryset = OperationModel.objects.all()
    serializer_class = OperationDetailSerializer
    lookup_field = 'pk'
    lookup_url_kwarg = 'operationID'























class QuestionPagination(PageNumberPagination):
    page_size = 5
    page_query_param = "page"
    page_size_query_param = "size"
    max_page_size = 10

class QuestionListView(ListAPIView):
    serializer_class = QuestionSerializer
    pagination_class = QuestionPagination
    filter_backends = [OrderingFilter,DjangoFilterBackend]
    filterset_fields = ['department', 'treatment']
    ordering_fields = ['created_time','view_count']
    ordering = ['-created_time']

    def get_queryset(self):
        departmentID = int(self.kwargs.get('departmentID',0))
        treatmentID = int(self.kwargs.get('treatmentID',0))
        query_set = QuestionModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
        if departmentID>0:
            query_set = query_set.filter(department=departmentID)
        if treatmentID>0:
            query_set = query_set.filter(treatment=treatmentID)
        return query_set

class QuestionDetailView(RetrieveAPIView):
    queryset = QuestionModel.objects.filter(is_deleted=False, is_show=True)
    serializer_class = QuestionDetailSerializer
    lookup_url_kwarg = 'questionID'

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.view_count += 1
        instance.save()
        return super().retrieve(request, *args, **kwargs)

class AnswerListView(ListAPIView):
    serializer_class = AnswerSerializer
    def get_queryset(self):
        questionID = int(self.kwargs.get('questionID',0))
        query_set = AnswerModel.objects.filter(is_deleted=False, is_show=True).order_by('id')
        if questionID>0:
            query_set = query_set.filter(question=questionID)
        return query_set

# 搜索
class DoctorSearchView(HaystackViewSet):
    index_models = [DoctorModel]
    serializer_class = DoctorIndexHaystackSerializer
    filter_backends = [OrderingFilter, HaystackFilter]
    ordering_fields = ('id','rating','consultation_price','avg_response_time')

